package com.gaojinqi.sys.core.shiro.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.util.Objects;

/**
 * @author gaojinqi
 * @version 1.0
 * @since 2020年04月21日
 */
public class PasswordHelper {

    private final static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private static String ALGORITHM_NAME = "md5";
    private static final int hashIterations = 2;

    /**
     * 生成随机盐值
     */
    public static String generateSalt() {
        return randomNumberGenerator.nextBytes().toHex();
    }

    /**
     * 加密密码
     */
    public static String encryptPassword(String password, String salt) {
        return new SimpleHash(
                ALGORITHM_NAME,
                password,
                ByteSource.Util.bytes(salt),
                hashIterations).toHex();
    }

    /**
     * 匹配密码是否相等
     *
     * @param plaintext 明文密码
     * @param ciphetext 密文密码
     * @param salt      盐值
     */
    public static boolean match(String plaintext, String ciphetext, String salt) {
        if (plaintext == null || ciphetext == null || salt == null) {
            return false;
        }
        return Objects.equals(ciphetext, encryptPassword(plaintext, salt));
    }

}
